/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package merlion.common.session.stateless;

import java.util.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import merlion.common.entity.Announcement;
import merlion.common.entity.SecurityRole;
import merlion.common.entity.Staff;
import merlion.common.entity.SystemUserAccount;

/**
 *
 * @author Zhang Ying
 */
@Stateless
public class AnnouncementSession implements AnnouncementSessionLocal {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void addNewAnnouncement(Announcement a) {
        try {
            // set date
            Calendar calendar = Calendar.getInstance();
            Date date = calendar.getTime();
            Timestamp currentTime = new Timestamp(date.getTime());
            a.setAnnounceDate(currentTime);
            // merge
            entityManager.merge(a);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Collection<Announcement> getAllMyMgedAnnouncements(Long posterId) {
        Query query = entityManager.createQuery("SELECT a FROM Announcement a WHERE a.posterId=:p1");
        query.setParameter("p1", posterId);
        return (List<Announcement>) query.getResultList();
    }

    @Override
    public Announcement getAnnouncement(Long id) {
        return entityManager.find(Announcement.class, id);
    }

    @Override
    public boolean deleteAnnouncement(Long id) {
        Announcement ann = entityManager.find(Announcement.class, id);
        try {
            ann.setAudience(null);
            entityManager.merge(ann);
            entityManager.remove(ann);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteManyAnnouncements(Announcement[] anns) {
        try{
            int i = 0;
            Announcement ann;
            while (i < anns.length){
                ann = entityManager.find(Announcement.class, anns[i].getId());
                ann.setAudience(null);
                entityManager.merge(ann);
                entityManager.remove(ann);
                i++;
            }
            return true;
        }catch(Exception ex){
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateAnnouncement(Announcement a) {
        try{
            entityManager.merge(a);
            return true;
        }catch(Exception ex){
            return false;
        }
    }

    @Override
    public Staff getPoster(Long posterId) {
        return entityManager.find(Staff.class, posterId);
    }

    @Override
    public Collection<Announcement> getAllMyAnnouncements(Staff currentStaff) {
        Collection<SecurityRole> srs = currentStaff.getSecurityRoles();
        Collection<Announcement> myAnns = new ArrayList<Announcement>();
        Query query = entityManager.createQuery("SELECT a FROM Announcement a");
        Collection<Announcement> allAnns = (List<Announcement>) query.getResultList();
        for (Announcement ann : allAnns){
            for (SecurityRole sr : srs){
                if (ann.getAudience().contains(sr) && !myAnns.contains(ann)){
                    myAnns.add(ann);
                }
            }
        }
        return myAnns;
    }

    @Override
    public Collection<Announcement> getRecentAtMostFiveAnns(Long accId) {
        SystemUserAccount sua = entityManager.find(SystemUserAccount.class, accId);
        List<Announcement> result = (List<Announcement>) getAllMyAnnouncements(sua.getStaff());
        // sort the announcement by date
        for (int i = 0; i < result.size()-1; i++){
            for (int j= 0 ; j < result.size(); j++){
                if (result.get(i).getAnnounceDate().compareTo(result.get(j).getAnnounceDate()) < 0 ){
                    Announcement atemp = result.get(i);
                    result.set(i, result.get(j));
                    result.set(j, atemp);
                }
            }
        }
        if (result.size() <= 5){
            return result;
        }else{
            Collection<Announcement> newRes = new ArrayList<Announcement>();
            for (int i = 0; i < 5; i++){
                newRes.add(result.get(i));
            }
            return newRes;
        }
    }
    
}
